package top.littlejiang.onlinexam.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import top.littlejiang.onlinexam.common.base.BasePage;
import top.littlejiang.onlinexam.common.base.Constant;
import top.littlejiang.onlinexam.common.utils.DateUtils;
import top.littlejiang.onlinexam.common.utils.JSONUtils;
import top.littlejiang.onlinexam.common.utils.JWTUtils;
import top.littlejiang.onlinexam.entity.OlexamQuestions;
import top.littlejiang.onlinexam.mapper.OlexamQuestionsMapper;
import top.littlejiang.onlinexam.service.OlexamCourseService;
import top.littlejiang.onlinexam.service.OlexamFileService;
import top.littlejiang.onlinexam.service.OlexamQuestionsService;
import top.littlejiang.onlinexam.common.base.BaseServiceImpl;
import org.springframework.stereotype.Service;
import top.littlejiang.onlinexam.vo.QuestionQueryVO;

import java.io.Serializable;
import java.util.*;

/**
 * <p>
 * 题目表 服务实现类
 * </p>
 *
 * @author chen
 * @since 2021-03-11
 */
@Service
public class OlexamQuestionsServiceImpl extends BaseServiceImpl<OlexamQuestionsMapper, OlexamQuestions> implements OlexamQuestionsService {


    @Autowired
    OlexamCourseService courseService;
    @Autowired
    OlexamFileService fileService;

    /**
     * 分页查询
     *
     * @param page
     * @return
     */
    @Override
    public IPage<OlexamQuestions> getQuestionListPage(BasePage<QuestionQueryVO> page) {
        QuestionQueryVO query = page.getQueryParam();
        QueryWrapper<OlexamQuestions> wrapper = new QueryWrapper<>();
        List<String> courses = courseService.selectByteacher(JWTUtils.getUserId());
        if (!CollectionUtils.isEmpty(courses)){
            wrapper.in("fk_course_name", courses);
        }
        if (!StringUtils.isBlank(query.getTitleDetail())){
            wrapper.like("title_detail", query.getTitleDetail());
        }
        if (!StringUtils.isBlank(query.getType())){
            wrapper.eq("type", query.getType());
        }
        if (!StringUtils.isBlank(query.getFkCourseName())){
            wrapper.eq("fk_course_name", query.getFkCourseName());
        }
        if (page.getPageSize() <= 0){
            page.setPageSize(10);
        }
        wrapper.eq("is_del", 0);
        Page<OlexamQuestions> p = new Page<>(page.getPageIndex(), page.getPageSize());
        IPage<OlexamQuestions> pages = this.baseMapper.getQuestionList(p, wrapper);
        return pages;
    }

    /**
     * 保存或更新题目
     *
     * @param question
     * @param files
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void insertOrUpdate(OlexamQuestions question, MultipartFile[] files) {
        List<Map<String, String>> imgList = new ArrayList<>();
        if (!Objects.isNull(files)){
            for (MultipartFile file : files){
                String fileUrl = fileService.saveFile(file, Constant.PICTURE_URL);
                Map<String, String> temp = new HashMap<>(2);
                temp.put("name", file.getOriginalFilename());
                temp.put("url", fileUrl);
                imgList.add(temp);
            }
        }
        JSONArray oldimgs = JSONUtils.jsonToBean(question.getImgList(), JSONArray.class);
        if (!CollectionUtils.isEmpty(oldimgs)){
            oldimgs.forEach(item -> imgList.add((Map)item));
        }
        question.setImgList(JSONUtils.beanToJson(imgList));
        question.setUpdateTime(DateUtils.getTime());
        if (question.getCreateUser() == null){
            question.setCreateUser(JWTUtils.getUserId());
        }
        if (question.getId() == 0){
            question.setId(null);
        }
        this.saveOrUpdate(question);
    }

    /**
     * 根据条件查询所有内容
     *
     * @param queryVO
     * @return
     */
    @Override
    public List<OlexamQuestions> queryAll(QuestionQueryVO queryVO) {
        List<OlexamQuestions> rst = this.baseMapper.queryAll(queryVO);
        return rst;
    }

    /**
     * 根据id 获取详情
     *
     * @param ids
     * @param withAnswer 是否查询答案
     * @return
     */
    @Override
    public List<OlexamQuestions> selectInIds(List<Serializable> ids, boolean withAnswer) {
        QueryWrapper<OlexamQuestions> wrapper = new QueryWrapper<>();
        String selectStr = "id,type,fk_course_name,title_detail,selection_list,img_list,score,remarks";
        if (withAnswer){
            selectStr = selectStr + ",answer";
        }
        wrapper.select(selectStr)
                .eq("is_del", 0)
                .in("id", ids);
        return list(wrapper);
    }
}
